﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Linq.Expressions;
using Yala.Core.Domain;

namespace Yala.UnitTests.FakeDependencies.Repositories {
    public abstract class FakeRepositoryBase<T> : IRepository<T> where T : class, new() {

        IList<T> _collection;
        protected FakeRepositoryBase() {
            _collection = new List<T>();
        }

        public void Add(T item) {
            _collection.Add(item);
        }

        public void Add(IEnumerable<T> items) {
            foreach (var item in items)
                this.Add(item);
        }

        public void Update(T item) {
            if (_collection.Contains(item))
                _collection.Remove(item);

            _collection.Add(item);
        }

        public void Delete(Expression<Func<T, bool>> expression) {
            var items = _collection.AsQueryable().Where(expression).ToList();
            foreach (var item in items)
                this.Delete(item);
        }

        public void Delete(T item) {
            if (_collection.Contains(item))
                _collection.Remove(item);
        }

        public void DeleteAll() {
            foreach (var item in _collection)
                this.Delete(item);
        }

        public void CommitChanges() {
        }

        public T Single(Expression<Func<T, bool>> expression) {
            return _collection.AsQueryable().Where(expression).FirstOrDefault();
        }

        public IQueryable<T> All() {
            return _collection.AsQueryable();
        }

        public void Dispose() {
            // Do nothing            
        }
    }
}
